const {
	db,
	dbCmd,
	result_success,
	result_error,
	appletInfoCollection,
	userCollection
} = require('../../common/constants')
module.exports = async function(params = {}) {
	const token = this.getUniIdToken()
	if (!token) {
		return result_error('登录失效,请重新登录')
	}
	let payload = await this.uniID.checkToken(token)
	if (payload.code) {
		return payload
	}
	let cUser = await userCollection.doc(payload.uid).get()
	cUser = cUser.data[0]
	//获取当前应用
	let appletInfoData = await appletInfoCollection.doc(cUser.app_id).get()
	appletInfoData = appletInfoData.data[0]
	let employeeUser = await userCollection.where({
		mobile: params.mobile
	}).get()
	employeeUser = employeeUser.data
	if (employeeUser.length > 0) {
		return result_error('用户已存在')
	}
	let role = []
	if (params.type === 0) {
		params.type_name = '经理'
		role = ['shop_admin_handle']
	} else if (params.type === 1) {
		params.type_name = '员工'
		role = ['shop_admin_staff']
	} else if (params.type === 2) {
		params.type_name = '财务'
		role = ['shop_admin_finance']
	}
	params.app_id = appletInfoData._id
	params.shop_id = appletInfoData._id
	params.creator_id = payload.uid
	params.create_time = new Date().getTime()
	await db.collection('wmzmall-employee').add(params)

	let userData = {
		"dcloud_appid": [
			"__UNI__9B2AD81"
		],
		"mobile": params.mobile,
		"mobile_confirmed": 1,
		"nickname": params.name,
		"password": "3b91bb6d75cc2ad6598bd206af5acfe8928d0a9b",
		"role": role,
		"status": 0,
		"tags": [],
		"username": "wmz_" + params.mobile,
		app_id:params.app_id,
		shop_id:params.shop_id
	}
	let res = await userCollection.add(userData)

	return result_success()
}